#!/bin/bash
# make raspi image inchroot

# product
# version
# release
# repo_url
# packages
# upload_image_dir


. ${LKP_SRC}/lib/upload.sh
. ${LKP_SRC}/lib/debug.sh
. ${LKP_SRC}/lib/create_compile_env.sh


init_image_tailor()
{
	if rpm -q imageTailor &> /dev/null; then
		yum remove -y imageTailor
	fi
	yum install -y imageTailor sudo -c ${yum_conf} || die "install imageTailor error."
}

modify_config_file()
{
	config_path="/opt/imageTailor/custom/cfg_raspi/config"
	repo_file="${config_path}/openeuler.repo"
	rpmlist_file="${config_path}/rpmlist"
	
	rm -f ${repo_file} && cp ${yum_conf} ${repo_file}

	echo "" >> ${rpmlist_file}
	for pkg in ${packages[@]}
	do
		echo "${pkg}" >> ${rpmlist_file}
	done
}

modify_pwd_file()
{
	config_path="/opt/imageTailor/custom/cfg_raspi/config"
	pi_pwd_file="${config_path}/pi_pwd"
	root_pwd_file="${config_path}/root_pwd"

	echo '$6$sXb59.e3yHqYhPUX$H1vUD9X0N1fpeAFDL5VEGcf70iAqFh2drjhnzJU3A9uaqbV7i4fTafsoteZdMbuWC6fqetlYNpmuLsQKDl2bM.' > "${pi_pwd_file}"
	echo '$6$o4rTi3d/.hh6JUYC$ClnCxd2mAQHlt0UloC4ystQg0CiuSVyhXz0sP1mDCNCgWV0rBwegwJ/bCWfjN4WxbahDa7F9U3c6/vFaNgsvX/' > "${root_pwd_file}"
}


build_image()
{
	cd /opt/imageTailor/
	./mkdliso -p raspi -c custom/cfg_raspi
}

upload_image()
{
	ARCH="$(uname -i)"
	if [ -n "${release}" ];then
		raspi_img="${product}-${version}-${release}-raspi-${ARCH}.img"
		raspi_img_xz="${raspi_img}.xz"
	else
		raspi_img="${product}-${version}-raspi-${ARCH}.img"
		raspi_img_xz="${raspi_img}.xz"
	fi
	
	raspi_image_file=(${raspi_img} ${raspi_img_xz} ${raspi_img}.sha256sum ${raspi_img_xz}.sha256sum)
	cd "/opt/imageTailor/result/$(date +%Y)"*
	if [ ! -s "raspi-${ARCH}.img" ] || [ ! -s "raspi-${ARCH}.img.xz" ];then
		die "make raspi failed."
	fi

	mv "raspi-${ARCH}.img" ${raspi_img}
	sha256sum ${raspi_img} > "${raspi_img}.sha256sum"
	mv "raspi-${ARCH}.img.xz" ${raspi_img_xz}
	sha256sum ${raspi_img_xz} > "${raspi_img_xz}.sha256sum"
	
	for file_name in ${raspi_image_file[@]}
	do
		upload_one_curl "${file_name}" ${upload_image_dir}
		if [ $? -ne 0 ];then
			die "upload image failed."
		fi
	done
}

build_raspi_image()
{
	config_env_repo
	init_image_tailor
	modify_config_file
	modify_pwd_file
	build_image
	upload_image
}

trap abnormal_exit EXIT

build_raspi_image
if [ $? -eq 0 ];then
	status="success"
fi
